package com.ikangtai.shecare.main;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.Constant;
import com.ikangtai.shecare.common.DownloadService;
import com.ikangtai.shecare.common.EnConstant;
import com.ikangtai.shecare.common.RecordFragmentCommonList;
import com.ikangtai.shecare.common.al.Algorithm;
import com.ikangtai.shecare.common.al.DayUnitDSOutput;
import com.ikangtai.shecare.common.al.UserUnitDS;
import com.ikangtai.shecare.common.baseView.ListBar;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.baseView.articleList.ArticleAdapter;
import com.ikangtai.shecare.common.baseView.articleList.ArticleBean;
import com.ikangtai.shecare.common.baseView.collectionList.CollectionBean;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.db.sync.SyncCompleteTask;
import com.ikangtai.shecare.common.eventBusMsg.AlgoUpdateMsg;
import com.ikangtai.shecare.common.eventBusMsg.BatteryVolumeMsg;
import com.ikangtai.shecare.common.eventBusMsg.ChooseStateMsg;
import com.ikangtai.shecare.common.eventBusMsg.ConnectStateMsg;
import com.ikangtai.shecare.common.eventBusMsg.CurveMsg;
import com.ikangtai.shecare.common.eventBusMsg.DelCollectedArticle;
import com.ikangtai.shecare.common.eventBusMsg.FoundNewVersionMsg;
import com.ikangtai.shecare.common.eventBusMsg.RecordInfo;
import com.ikangtai.shecare.common.eventBusMsg.WebviewInitDataMsg;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncCompleteTaskMsg;
import com.ikangtai.shecare.common.httpBean.GetAllTask;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.common.util.InternetUtil;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.ikangtai.shecare.common.util.SDCardHelper;
import com.ikangtai.shecare.common.util.TasksUtil;
import com.ikangtai.shecare.common.util.UpdateUtil;
import com.ikangtai.shecare.home.HomeSysTask;
import com.ikangtai.shecare.home.ModifyTaskListActivity;
import com.ikangtai.shecare.home.calendar.CalendarActivity;
import com.ikangtai.shecare.home.calendar.DayState;
import com.ikangtai.shecare.home.circlecalendar.Calendar;
import com.ikangtai.shecare.home.circlecalendar.FlipViewPager;
import com.ikangtai.shecare.home.circlecalendar.PageAdapter;
import com.ikangtai.shecare.home.circlecalendar.ZoomOutPageTransformer;
import com.ikangtai.shecare.personal.MyDeviceChooseActivity;
import com.ikangtai.shecare.record.bean.UserRecordData;
import com.ikangtai.shecare.record.bean.UserTemperatureInfo;
import com.jaeger.library.StatusBarUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment implements View.OnClickListener, ListBar.OnListBarClickListener, PageAdapter.Callback {

    private ArrayList<Calendar> list;
    private FlipViewPager viewPager;
    private PageAdapter adapter;

    private int mLastPosition = 0;
    private TopBar topBar;
    private ImageView connectionStateImg;
    private TextView connectionStateText;
    private Button addTask;
    private LinearLayout taskTitleBottomLine, fragmentHomeUpperLayout;
    private ListBar taskBBT, taskWater, taskMedicine, taskSport, taskFruit, taskMucus, taskLHPaper, taskBUltrasonic;
    private int taskBBTBgColor, taskWaterBgColor, taskMedicineBgColor, taskSportBgColor, taskFruitBgColor, taskMucusBgColor, taskLHPaperBgColor, taskBUltrasonicBgColor;
    private int taskBBTBottomLineColor, taskWaterBottomLineColor, taskMedicineBottomLineColor, taskSportBottomLineColor, taskFruitBottomLineColor, taskMucusBottomLineColor, taskLHPaperBottomLineColor, taskBUltrasonicBottomLineColor;
    private static int anyTaskSelected = 0;
    private List<UserRecordData> userRecordDatas;
    private List<DayState> dayStates;
    private static final int RETRIEVE_ARTICLE_COUNT = 2;
    private static final int RETRIEVE_ARTICLE_LIST_OK = 200;
    private static final int RETRIEVE_ARTICLE_LIST_NOK = 404;
    private static final int TASK_INFO = 8;
    private static final int INSERT_TASK_OK = 9;
    private static final int INSERT_TASK_NOK = 10;
    private List<ArticleBean> articleBeanList = null;
    private List<ArticleBean> isCollectedBeanList = null;
    private BaseAdapter articleAdapter;
    private ListView articleListView;
    private DateUtil dateUtil = new DateUtil();
    private RelativeLayout bbtView;
    private TextView bbtText, mensesOrMucusText;
    private ImageView bbtIcon, mensesOrMucusIcon;
    private TasksUtil tasksUtil = new TasksUtil();
    private View view;
    private String dateRecord;
    private LinearLayout recordLayout;
    private float density;
    private AnimatorSet mRightOutSet; // 右出动画
    private AnimatorSet mLeftInSet; // 左入动画
    private int statePosition;
    private boolean isFromTop;
    private static final int ADD_ONE_DAY = 1;
    private static final int MINUS_ONE_DAY = -1;
    private String topbarDate;
    private int upperHeight;
    private String kTermType_BasalBodyTemperature, kTermType_FolicAcidExplain, kTermType_MucusExplain, kTermType_LHPaperExplain, kTermType_BUltrasonicExplain;
    private Algorithm algorithm;
    private String lastPeriodDateValue;
    private ProgressDialog progressDialog;

    public HomeFragment() {
        // Required empty public constructor
        EventBus.getDefault().register(this);
    }

    private DBManager dbManager;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        AppLog.i("LifeCycle get in HomeFragment onAttach!");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppLog.i("LifeCycle get in HomeFragment onCreate!");
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        AppLog.i("LifeCycle get in HomeFragment onViewCreated!");
    }

    @Override
    public void onStart() {
        super.onStart();
        AppLog.i("LifeCycle get in HomeFragment onStart!");
    }

    @Override
    public void onResume() {
        super.onResume();
        AppLog.i("LifeCycle get in HomeFragment onResume!");
    }

    @Override
    public void onPause() {
        super.onPause();
        AppLog.i("LifeCycle get in HomeFragment onPause!");

        // 215 多账号登陆时跳转至LoginActivity时取消掉dialog，否则再次登陆进来仍然可以看到此dialog
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        AppLog.i("LifeCycle get in HomeFragment onStop!");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        AppLog.i("LifeCycle get in HomeFragment onDestroyView!");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        AppLog.i("LifeCycle get in HomeFragment onDetach!");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        long t1 = System.currentTimeMillis();
        AppLog.i("get in HomeFragment start!");

        // Inflate the layout for this fragment
        density = getResources().getDisplayMetrics().density;
        dayStates = new ArrayList<>();
        userRecordDatas = new ArrayList<>();
        App.savePreference("density", (int) density);
        Log.d("density", density + "");
        view = inflater.inflate(R.layout.fragment_home, container, false);
        initView(view);
        // 实例化tabhost

        view.findViewById(R.id.connectionStateLayout).setOnClickListener(this);
        view.findViewById(R.id.recordLayout).setOnClickListener(this);
        algorithm = new Algorithm(this.getActivity());
        Intent intent = getActivity().getIntent();
        int isNeedFirstAL = intent.getIntExtra("isNeedFirstExecAL", 0);
        AppLog.e("isNeedFirstAL:" + isNeedFirstAL + " memory_preference_lastPeriodDate:" + App.memory_preference_lastPeriodDate);
        if (null == App.memory_preference_lastPeriodDate || "".equals(App.memory_preference_lastPeriodDate) || isNeedFirstAL == 1) {
            showInputLastPeriodDateDialog();
        }
        long t2 = System.currentTimeMillis();
        AppLog.i("get in HomeFragment end! time = " + (t2 - t1));
        return view;
    }

    private int getCurrentPosition() {
        int position = 0;
        for (int i = 0; i < App.dayUnitDSOutputsList.size(); i++) {
            if (dateUtil.getCircleCalendarDate().equals(dateUtil.getCircleCalendarDate2(App.dayUnitDSOutputsList.get(i).date))) {
                position = i;
            }
        }
        return position;
    }

    private void initView(View view) {

        topBar = (TopBar) view.findViewById(R.id.topBar);
        topBar.setText(dateUtil.getDateTopBar());
        dbManager = new DBManager(getActivity());
        dateRecord = topBar.getText().split(" ")[0];
        MainActivity.chosedDateCalendar = dateRecord;

        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                toToday(getCurrentPosition());
                App.savePreference(Constant.kStatusColor, getBGColor(getCurrentPosition()));
                App.savePreference(Constant.kStatusDay, topBar.getText());
            }

            @Override
            public void midLeftClick() {
                isFromTop = true;
                if (statePosition >= 2) {
                    changeTopBarDate(MINUS_ONE_DAY);
                    toToday(--statePosition);
                }
                App.savePreference(Constant.kStatusColor, getBGColor(statePosition));
                App.savePreference(Constant.kStatusDay, topBar.getText());
                setBBT();
            }

            @Override
            public void midRightClick() {
                isFromTop = true;
                if (statePosition <= list.size() - 5) {
                    changeTopBarDate(ADD_ONE_DAY);
                    toToday(++statePosition);
                }
                App.savePreference(Constant.kStatusColor, getBGColor(statePosition));
                App.savePreference(Constant.kStatusDay, topBar.getText());
                setBBT();
            }

            @Override
            public void rightClick() {
                AppLog.i("calendarImgView clicked!");
                Intent intent = new Intent();

                intent.setClass(getContext(), CalendarActivity.class);
                startActivity(intent);
//                startActivity(new Intent(getContext(), Activitycccc.class));
            }
        });

        addTask = (Button) view.findViewById(R.id.addTask);
        taskTitleBottomLine = (LinearLayout) view.findViewById(R.id.taskTitleBottomLine);
        taskBBT = (ListBar) view.findViewById(R.id.taskBBT);
        taskWater = (ListBar) view.findViewById(R.id.taskWater);
        taskMedicine = (ListBar) view.findViewById(R.id.taskMedicine);
        taskSport = (ListBar) view.findViewById(R.id.taskSport);
        taskFruit = (ListBar) view.findViewById(R.id.taskFruit);
        taskMucus = (ListBar) view.findViewById(R.id.taskMucus);
        taskLHPaper = (ListBar) view.findViewById(R.id.taskLHPaper);
        taskBUltrasonic = (ListBar) view.findViewById(R.id.taskBUltrasonic);
        fragmentHomeUpperLayout = (LinearLayout) view.findViewById(R.id.fragment_home_upper_layout);
        fragmentHomeUpperLayout.setFocusable(true);
        fragmentHomeUpperLayout.setFocusableInTouchMode(true);
        fragmentHomeUpperLayout.requestFocus();
        recordLayout = (LinearLayout) view.findViewById(R.id.recordLayout);
        addTask.setOnClickListener(this);

        taskBBT.setOnClickListener(this);
        taskBBT.setOnListBarClickListener(this);

        taskWater.setOnClickListener(this);
        taskWater.setOnListBarClickListener(this);

        taskMedicine.setOnClickListener(this);
        taskMedicine.setOnListBarClickListener(this);

        taskSport.setOnClickListener(this);
        taskSport.setOnListBarClickListener(this);

        taskFruit.setOnClickListener(this);
        taskFruit.setOnListBarClickListener(this);

        taskMucus.setOnClickListener(this);
        taskMucus.setOnListBarClickListener(this);

        taskLHPaper.setOnClickListener(this);
        taskLHPaper.setOnListBarClickListener(this);

        taskBUltrasonic.setOnClickListener(this);
        taskBUltrasonic.setOnListBarClickListener(this);

        taskBBTBgColor = R.color.task_selected_bbt_bg_color;
        taskWaterBgColor = R.color.task_selected_water_bg_color;
        taskMedicineBgColor = R.color.task_selected_medicine_bg_color;
        taskSportBgColor = R.color.task_selected_sport_bg_color;
        taskFruitBgColor = R.color.task_selected_fruit_bg_color;
        taskMucusBgColor = R.color.task_selected_mucus_bg_color;
        taskLHPaperBgColor = R.color.task_selected_lh_paper_bg_color;
        taskBUltrasonicBgColor = R.color.task_selected_b_ultrasonic_bg_color;

        taskBBTBottomLineColor = R.color.task_selected_bbt_bottom_line_color;
        taskWaterBottomLineColor = R.color.task_selected_water_bottom_line_color;
        taskMedicineBottomLineColor = R.color.task_selected_medicine_bottom_line_color;
        taskSportBottomLineColor = R.color.task_selected_sport_bottom_line_color;
        taskFruitBottomLineColor = R.color.task_selected_fruit_bottom_line_color;
        taskMucusBottomLineColor = R.color.task_selected_mucus_bottom_line_color;
        taskLHPaperBottomLineColor = R.color.task_selected_lh_paper_bottom_line_color;
        taskBUltrasonicBottomLineColor = R.color.task_selected_b_ultrasonic_bottom_line_color;

        bbtView = (RelativeLayout) view.findViewById(R.id.home_bbt_today);
        bbtText = (TextView) view.findViewById(R.id.home_bbt_today_value);
        bbtIcon = (ImageView) view.findViewById(R.id.home_bbt_icon);
        mensesOrMucusText = (TextView) view.findViewById(R.id.home_menses_or_mucus_value);
        mensesOrMucusIcon = (ImageView) view.findViewById(R.id.home_menses_or_mucus_icon);

        articleListView = (ListView) view.findViewById(R.id.articleListView);
        connectionStateImg = (ImageView) view.findViewById(R.id.connectionStateImg);
        connectionStateText = (TextView) view.findViewById(R.id.connectionStateText);
        connectionStateText.setOnClickListener(this);
        if (null != App.memory_preference_macAddress && !"".equals(App.memory_preference_macAddress)) {
            connectionStateText.setText(getResources().getString(R.string.un_connection));
        } else {
            connectionStateText.setText(getResources().getString(R.string.not_paired));
        }


        topbarDate = dateUtil.getSimpleDate();
        taskInfo();
        taskSelectInfo(topbarDate);
        initCalendar(view);
        App.savePreference(Constant.kCurrentPosition, getCurrentPosition());
    }

    /**
     * @param someTask   task对象
     * @param taskName   task内容
     * @param kBegin     关键词开始位置
     * @param kEnd       关键词结束位置
     * @param nBegin     其他开始
     * @param nEnd       其他结束
     * @param key        task关键词
     * @param detail     task关键词描述
     * @param ulColor    关键词下划线颜色
     * @param noColor    正常字体颜色
     * @param rbDrawable 右侧button图标
     * @param lbDrawable 左侧button图标
     */

    private void SetTask(ListBar someTask, String taskName, int kBegin, int kEnd, int nBegin, int nEnd,
                         final String key, final String detail,
                         int ulColor, int noColor, int rbDrawable, int lbDrawable) {
        SpannableString taskDetail = new SpannableString(taskName);
        taskDetail.setSpan(new UnderlineSpan(), kBegin, kEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        taskDetail.setSpan(new ForegroundColorSpan(ulColor), kBegin, kEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        taskDetail.setSpan(new ForegroundColorSpan(noColor), nBegin, nEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        someTask.setmMidTextView(taskDetail);
        someTask.setClickable(true);
        someTask.setMidClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String updateAlertTitle = key;
                String updateAlertMsg = detail;
                String updateAlertPositiveButtonTxt = getString(R.string.saveTask_make_sure);
                Dialog dialog = new AlertDialog.Builder(getContext()).setTitle(updateAlertTitle)
                        .setMessage(updateAlertMsg)
                        .setCancelable(false)
                        .setPositiveButton(updateAlertPositiveButtonTxt, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }
                        ).create();
                dialog.show();
            }
        });
        someTask.setmRightButton(rbDrawable);
        someTask.setmLeftButton(lbDrawable);

    }

    /**
     * @param someTask   task对象
     * @param taskName   task内容
     * @param size       task长度
     * @param noColor    task颜色
     * @param rbDrawable task右图案
     * @param lbDrawable task左图案
     */
    private void SetTask(ListBar someTask, String taskName, int size,
                         int noColor, int rbDrawable, int lbDrawable) {
        SpannableString taskDetail = new SpannableString(taskName);
        taskDetail.setSpan(new ForegroundColorSpan(noColor), 0, size, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        someTask.setmMidTextView(taskDetail);
        someTask.setClickable(true);
        someTask.setmRightButton(rbDrawable);
        someTask.setmLeftButton(lbDrawable);

    }


    private void SetTextStyleBefore() {

        if (dbManager.getHomeSysTask().size() == 0) {
            if (InternetUtil.hasInternet()) {
                Observable.create(new Observable.OnSubscribe<Boolean>() {
                    @Override
                    public void call(Subscriber<? super Boolean> subscriber) {
                        subscriber.onNext(getAllTask());
                    }
                }).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<Boolean>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(Boolean aBoolean) {
                                List<HomeSysTask> userRecordDataList = dbManager.getHomeSysTask();
                                switch (Locale.getDefault().getLanguage()) {
                                    case "zh":
                                        SetTask(taskBBT, userRecordDataList.get(0).getTask(),
                                                userRecordDataList.get(0).getGlossaryBegin(), userRecordDataList.get(0).getGlossaryEnd(),
                                                0, 2, userRecordDataList.get(0).getGlossary(), userRecordDataList.get(0).getTaskDetail(), Color.parseColor("#" + userRecordDataList.get(0).getGlossaryColor()),
                                                R.color.text_black, R.drawable.home_task_bbt_checkbox, R.drawable.home_task_bbt);
                                        SetTask(taskWater, userRecordDataList.get(1).getTask(), 6,
                                                getContext().getResources().getColor(R.color.text_black), R.drawable.home_task_water_checkbox, R.drawable.home_task_water);


                                        SetTask(taskMedicine, userRecordDataList.get(2).getTask(),
                                                userRecordDataList.get(2).getGlossaryBegin(), userRecordDataList.get(2).getGlossaryEnd(),
                                                0, 2, userRecordDataList.get(2).getGlossary(), userRecordDataList.get(2).getTaskDetail(), Color.parseColor("#" + userRecordDataList.get(2).getGlossaryColor()),
                                                R.color.text_black, R.drawable.home_task_medicine_checkbox, R.drawable.home_task_medicine);

                                        SetTask(taskSport, userRecordDataList.get(3).getTask(), 4,
                                                getContext().getResources().getColor(R.color.text_black), R.drawable.home_task_sport_checkbox, R.drawable.home_task_sport);

                                        SetTask(taskFruit, userRecordDataList.get(4).getTask(), 3,
                                                getContext().getResources().getColor(R.color.text_black), R.drawable.home_task_fruit_checkbox, R.drawable.home_task_fruit);

                                        SetTask(taskMucus, userRecordDataList.get(5).getTask(),
                                                userRecordDataList.get(5).getGlossaryBegin(), userRecordDataList.get(5).getGlossaryEnd(),
                                                0, 2, userRecordDataList.get(5).getGlossary(), userRecordDataList.get(5).getTaskDetail(), Color.parseColor("#" + userRecordDataList.get(5).getGlossaryColor()),
                                                R.color.text_black, R.drawable.home_task_mucus_checkbox, R.drawable.home_task_mucus);

                                        SetTask(taskLHPaper, userRecordDataList.get(6).getTask(),
                                                userRecordDataList.get(6).getGlossaryBegin(), userRecordDataList.get(6).getGlossaryEnd(),
                                                0, 2, userRecordDataList.get(6).getGlossary(), userRecordDataList.get(6).getTaskDetail(), Color.parseColor("#" + userRecordDataList.get(6).getGlossaryColor()),
                                                R.color.text_black, R.drawable.home_task_lh_paper_checkbox, R.drawable.home_task_lh_paper);

                                        SetTask(taskBUltrasonic, userRecordDataList.get(7).getTask(),
                                                userRecordDataList.get(7).getGlossaryBegin(), userRecordDataList.get(7).getGlossaryEnd(),
                                                2, 4, userRecordDataList.get(7).getGlossary(), userRecordDataList.get(7).getTaskDetail(), Color.parseColor("#" + userRecordDataList.get(7).getGlossaryColor()),
                                                R.color.text_black, R.drawable.home_task_b_ultrasonic_checkbox, R.drawable.home_task_b_ultrasonic);
                                        break;
                                    default:
                                        SetTask(taskBBT, userRecordDataList.get(0).getTaskEn(),
                                                userRecordDataList.get(0).getGlossaryBeginEn(), userRecordDataList.get(0).getGlossaryEndEn(),
                                                0, 7, userRecordDataList.get(0).getGlossaryEn(), userRecordDataList.get(0).getTaskDetailEn(), Color.parseColor("#" + userRecordDataList.get(0).getGlossaryColor()),
                                                R.color.text_black, R.drawable.home_task_bbt_checkbox, R.drawable.home_task_bbt);


                                        SetTask(taskWater, userRecordDataList.get(1).getTaskEn(), 6,
                                                getContext().getResources().getColor(R.color.text_black), R.drawable.home_task_water_checkbox, R.drawable.home_task_water);


                                        SetTask(taskMedicine, userRecordDataList.get(2).getTaskEn(),
                                                userRecordDataList.get(2).getGlossaryBeginEn(), userRecordDataList.get(2).getGlossaryEndEn(),
                                                0, 4, userRecordDataList.get(2).getGlossaryEn(), userRecordDataList.get(2).getTaskDetailEn(), Color.parseColor("#" + userRecordDataList.get(2).getGlossaryColor()),
                                                R.color.text_black, R.drawable.home_task_medicine_checkbox, R.drawable.home_task_medicine);

                                        SetTask(taskSport, userRecordDataList.get(3).getTaskEn(), 4,
                                                getContext().getResources().getColor(R.color.text_black), R.drawable.home_task_sport_checkbox, R.drawable.home_task_sport);

                                        SetTask(taskFruit, userRecordDataList.get(4).getTaskEn(), 3,
                                                getContext().getResources().getColor(R.color.text_black), R.drawable.home_task_fruit_checkbox, R.drawable.home_task_fruit);

                                        SetTask(taskMucus, userRecordDataList.get(5).getTaskEn(),
                                                userRecordDataList.get(5).getGlossaryBeginEn(), userRecordDataList.get(5).getGlossaryEndEn(),
                                                0, 5, userRecordDataList.get(5).getGlossaryEn(), userRecordDataList.get(5).getTaskDetailEn(), Color.parseColor("#" + userRecordDataList.get(5).getGlossaryColor()),
                                                R.color.text_black, R.drawable.home_task_mucus_checkbox, R.drawable.home_task_mucus);

                                        SetTask(taskLHPaper, userRecordDataList.get(6).getTaskEn(),
                                                userRecordDataList.get(6).getGlossaryBeginEn(), userRecordDataList.get(6).getGlossaryEndEn(),
                                                0, 9, userRecordDataList.get(6).getGlossaryEn(), userRecordDataList.get(6).getTaskDetailEn(), Color.parseColor("#" + userRecordDataList.get(6).getGlossaryColor()),
                                                R.color.text_black, R.drawable.home_task_lh_paper_checkbox, R.drawable.home_task_lh_paper);

                                        SetTask(taskBUltrasonic, userRecordDataList.get(7).getTaskEn(),
                                                userRecordDataList.get(7).getGlossaryBeginEn(), userRecordDataList.get(7).getGlossaryEndEn(),
                                                11, 21, userRecordDataList.get(7).getGlossaryEn(), userRecordDataList.get(7).getTaskDetailEn(), Color.parseColor("#" + userRecordDataList.get(7).getGlossaryColor()),
                                                R.color.text_black, R.drawable.home_task_b_ultrasonic_checkbox, R.drawable.home_task_b_ultrasonic);
                                }
                            }
                        });


            } else {
                Toast.makeText(getActivity(), getContext().getText(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            }

        } else {
            List<HomeSysTask> userRecordDataList = dbManager.getHomeSysTask();
            switch (Locale.getDefault().getLanguage()) {
                case "zh":
                    SetTask(taskBBT, userRecordDataList.get(0).getTask(),
                            userRecordDataList.get(0).getGlossaryBegin(), userRecordDataList.get(0).getGlossaryEnd(),
                            0, 2, userRecordDataList.get(0).getGlossary(), userRecordDataList.get(0).getTaskDetail(), Color.parseColor("#" + userRecordDataList.get(0).getGlossaryColor()),
                            R.color.text_black, R.drawable.home_task_bbt_checkbox, R.drawable.home_task_bbt);
                    SetTask(taskWater, userRecordDataList.get(1).getTask(), userRecordDataList.get(1).getTask().length(),
                            getContext().getResources().getColor(R.color.text_black), R.drawable.home_task_water_checkbox, R.drawable.home_task_water);


                    SetTask(taskMedicine, userRecordDataList.get(2).getTask(),
                            userRecordDataList.get(2).getGlossaryBegin(), userRecordDataList.get(2).getGlossaryEnd(),
                            0, 2, userRecordDataList.get(2).getGlossary(), userRecordDataList.get(2).getTaskDetail(), Color.parseColor("#" + userRecordDataList.get(2).getGlossaryColor()),
                            R.color.text_black, R.drawable.home_task_medicine_checkbox, R.drawable.home_task_medicine);

                    SetTask(taskSport, userRecordDataList.get(3).getTask(), userRecordDataList.get(3).getTask().length(),
                            getContext().getResources().getColor(R.color.text_black), R.drawable.home_task_sport_checkbox, R.drawable.home_task_sport);

                    SetTask(taskFruit, userRecordDataList.get(4).getTask(), userRecordDataList.get(4).getTask().length(),
                            getContext().getResources().getColor(R.color.text_black), R.drawable.home_task_fruit_checkbox, R.drawable.home_task_fruit);

                    SetTask(taskMucus, userRecordDataList.get(5).getTask(),
                            userRecordDataList.get(5).getGlossaryBegin(), userRecordDataList.get(5).getGlossaryEnd(),
                            0, 2, userRecordDataList.get(5).getGlossary(), userRecordDataList.get(5).getTaskDetail(), Color.parseColor("#" + userRecordDataList.get(5).getGlossaryColor()),
                            R.color.text_black, R.drawable.home_task_mucus_checkbox, R.drawable.home_task_mucus);

                    SetTask(taskLHPaper, userRecordDataList.get(6).getTask(),
                            userRecordDataList.get(6).getGlossaryBegin(), userRecordDataList.get(6).getGlossaryEnd(),
                            0, 2, userRecordDataList.get(6).getGlossary(), userRecordDataList.get(6).getTaskDetail(), Color.parseColor("#" + userRecordDataList.get(6).getGlossaryColor()),
                            R.color.text_black, R.drawable.home_task_lh_paper_checkbox, R.drawable.home_task_lh_paper);

                    SetTask(taskBUltrasonic, userRecordDataList.get(7).getTask(),
                            userRecordDataList.get(7).getGlossaryBegin(), userRecordDataList.get(7).getGlossaryEnd(),
                            2, 4, userRecordDataList.get(7).getGlossary(), userRecordDataList.get(7).getTaskDetail(), Color.parseColor("#" + userRecordDataList.get(7).getGlossaryColor()),
                            R.color.text_black, R.drawable.home_task_b_ultrasonic_checkbox, R.drawable.home_task_b_ultrasonic);
                    break;
                default:
                    SetTask(taskBBT, userRecordDataList.get(0).getTaskEn(),
                            userRecordDataList.get(0).getGlossaryBeginEn(), userRecordDataList.get(0).getGlossaryEndEn(),
                            0, 7, userRecordDataList.get(0).getGlossaryEn(), userRecordDataList.get(0).getTaskDetailEn(), Color.parseColor("#" + userRecordDataList.get(0).getGlossaryColor()),
                            R.color.text_black, R.drawable.home_task_bbt_checkbox, R.drawable.home_task_bbt);


                    SetTask(taskWater, userRecordDataList.get(1).getTaskEn(), userRecordDataList.get(1).getTask().length(),
                            getContext().getResources().getColor(R.color.text_black), R.drawable.home_task_water_checkbox, R.drawable.home_task_water);


                    SetTask(taskMedicine, userRecordDataList.get(2).getTaskEn(),
                            userRecordDataList.get(2).getGlossaryBeginEn(), userRecordDataList.get(2).getGlossaryEndEn(),
                            0, 4, userRecordDataList.get(2).getGlossaryEn(), userRecordDataList.get(2).getTaskDetailEn(), Color.parseColor("#" + userRecordDataList.get(2).getGlossaryColor()),
                            R.color.text_black, R.drawable.home_task_medicine_checkbox, R.drawable.home_task_medicine);

                    SetTask(taskSport, userRecordDataList.get(3).getTaskEn(), userRecordDataList.get(3).getTask().length(),
                            getContext().getResources().getColor(R.color.text_black), R.drawable.home_task_sport_checkbox, R.drawable.home_task_sport);

                    SetTask(taskFruit, userRecordDataList.get(4).getTaskEn(), userRecordDataList.get(4).getTask().length(),
                            getContext().getResources().getColor(R.color.text_black), R.drawable.home_task_fruit_checkbox, R.drawable.home_task_fruit);

                    SetTask(taskMucus, userRecordDataList.get(5).getTaskEn(),
                            userRecordDataList.get(5).getGlossaryBeginEn(), userRecordDataList.get(5).getGlossaryEndEn(),
                            0, 5, userRecordDataList.get(5).getGlossaryEn(), userRecordDataList.get(5).getTaskDetailEn(), Color.parseColor("#" + userRecordDataList.get(5).getGlossaryColor()),
                            R.color.text_black, R.drawable.home_task_mucus_checkbox, R.drawable.home_task_mucus);

                    SetTask(taskLHPaper, userRecordDataList.get(6).getTaskEn(),
                            userRecordDataList.get(6).getGlossaryBeginEn(), userRecordDataList.get(6).getGlossaryEndEn(),
                            0, 9, userRecordDataList.get(6).getGlossaryEn(), userRecordDataList.get(6).getTaskDetailEn(), Color.parseColor("#" + userRecordDataList.get(6).getGlossaryColor()),
                            R.color.text_black, R.drawable.home_task_lh_paper_checkbox, R.drawable.home_task_lh_paper);

                    SetTask(taskBUltrasonic, userRecordDataList.get(7).getTaskEn(),
                            userRecordDataList.get(7).getGlossaryBeginEn(), userRecordDataList.get(7).getGlossaryEndEn(),
                            11, 21, userRecordDataList.get(7).getGlossaryEn(), userRecordDataList.get(7).getTaskDetailEn(), Color.parseColor("#" + userRecordDataList.get(7).getGlossaryColor()),
                            R.color.text_black, R.drawable.home_task_b_ultrasonic_checkbox, R.drawable.home_task_b_ultrasonic);
            }
        }
    }

    private void SetTextStyleAfter() {
        SpannableString taskBBTt = new SpannableString(getContext().getString(R.string.task_bbt));
        taskBBTt.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.text_gray)), 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        taskBBT.setmMidTextView(taskBBTt);
        taskBBT.setClickable(false);
        taskBBT.setRightButtonClickAble(false);
        taskBBT.setmRightButton(R.drawable.home_modify_task_checkbox_default);
        taskBBT.setmLeftButton(R.drawable.home_task_bbt_disabled);

        SpannableString taskWatert = new SpannableString(getContext().getString(R.string.task_water));
        taskWatert.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.text_gray)), 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        taskWater.setmMidTextView(taskWatert);
        taskWater.setClickable(false);
        taskWater.setRightButtonClickAble(false);
        taskWater.setmRightButton(R.drawable.home_modify_task_checkbox_default);
        taskWater.setmLeftButton(R.drawable.home_task_water_disabled);

        SpannableString taskMedicinet = new SpannableString(getContext().getString(R.string.task_medicine));
        taskMedicinet.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.text_gray)), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        taskMedicine.setmMidTextView(taskMedicinet);
        taskMedicine.setClickable(false);
        taskMedicine.setRightButtonClickAble(false);
        taskMedicine.setmRightButton(R.drawable.home_modify_task_checkbox_default);
        taskMedicine.setmLeftButton(R.drawable.home_task_medicine_disabled);


        SpannableString taskMucust = new SpannableString(getContext().getString(R.string.task_mucus));
        taskMucust.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.text_gray)), 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        taskMucus.setmMidTextView(taskMucust);
        taskMucus.setClickable(false);
        taskMucus.setRightButtonClickAble(false);
        taskMucus.setmRightButton(R.drawable.home_modify_task_checkbox_default);
        taskMucus.setmLeftButton(R.drawable.home_task_mucus_disabled);


        SpannableString taskSportt = new SpannableString(getContext().getString(R.string.task_sport));
        taskSportt.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.text_gray)), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        taskSport.setmMidTextView(taskSportt);
        taskSport.setClickable(false);
        taskSport.setRightButtonClickAble(false);
        taskSport.setmRightButton(R.drawable.home_modify_task_checkbox_default);
        taskSport.setmLeftButton(R.drawable.home_task_sport_disabled);


        SpannableString taskFruitt = new SpannableString(getContext().getString(R.string.task_fruit));
        taskFruitt.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.text_gray)), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        taskFruit.setmMidTextView(taskFruitt);
        taskFruit.setClickable(false);
        taskFruit.setRightButtonClickAble(false);
        taskFruit.setmRightButton(R.drawable.home_modify_task_checkbox_default);
        taskFruit.setmLeftButton(R.drawable.home_task_fruit_disabled);


        SpannableString taskLHPapert = new SpannableString(getContext().getString(R.string.task_LHPaper));
        taskLHPapert.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.text_gray)), 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        taskLHPaper.setmMidTextView(taskLHPapert);
        taskLHPaper.setClickable(false);
        taskLHPaper.setRightButtonClickAble(false);
        taskLHPaper.setmRightButton(R.drawable.home_modify_task_checkbox_default);
        taskLHPaper.setmLeftButton(R.drawable.home_task_lhpaper_disabled);

        SpannableString task_BUltrasonict = new SpannableString(getContext().getString(R.string.task_BUltrasonic));
        task_BUltrasonict.setSpan(new ForegroundColorSpan(getContext().getResources().getColor(R.color.text_gray)), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        taskBUltrasonic.setmMidTextView(task_BUltrasonict);
        taskBUltrasonic.setClickable(false);
        taskBUltrasonic.setRightButtonClickAble(false);
        taskBUltrasonic.setmRightButton(R.drawable.home_modify_task_checkbox_default);
        taskBUltrasonic.setmLeftButton(R.drawable.home_task_buitrasonic_disabled);

    }

    private void showInputLastPeriodDateDialog() {

        Dialog alertDialog = new AlertDialog.Builder(getActivity()).
                setTitle(getString(R.string.warm_prompt)).
                setMessage(getString(R.string.menstruation_long_enter_again)).
                setPositiveButton(getString(R.string.sure), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setDateDialog();
                    }
                }).
                create();
        alertDialog.setCancelable(false);
        alertDialog.show();
    }

    private void setDateDialog() {
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        int year = calendar.get(java.util.Calendar.YEAR);
        int monthofYear = calendar.get(java.util.Calendar.MONTH);
        int dayofMonth = calendar.get(java.util.Calendar.DAY_OF_MONTH);
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String setLastPeriodDate = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                if (DateUtil.isFutureDate(year + "/" + (monthOfYear + 1) + "/" + dayOfMonth)) {
                    Toast.makeText(getActivity(), getString(R.string.future_time), Toast.LENGTH_SHORT).show();
                } else {
                    lastPeriodDateValue = setLastPeriodDate;
                    App.memory_preference_lastPeriodDate = setLastPeriodDate;
                    dbManager.updateUserPreference(App.userName, "lastPeriodDate", setLastPeriodDate);
                    initFirstAL();
                }
            }
        }, year, monthofYear, dayofMonth);
        dialog.setCancelable(false);
        DatePicker datePicker = dialog.getDatePicker();
        datePicker.setMaxDate(new Date().getTime());
        dialog.show();
    }

    private void initFirstAL() {
        showProgressDialog();
        UserUnitDS userData = new UserUnitDS();
        int mensesLen = App.memory_preference_mensesLen;
        if (mensesLen == 0) {
            mensesLen = 5;
            dbManager.updateUserPreference(App.userName, "mensesLen", "5");
            App.memory_preference_mensesLen = 5;
        }
        int periodLen = App.memory_preference_periodLen;
        if (periodLen == 0) {
            periodLen = 28;
            dbManager.updateUserPreference(App.userName, "periodLen", "28");
            App.memory_preference_periodLen = 28;
        }
        userData.averageMenstruationLength = mensesLen;
        userData.averageCycleLength = periodLen;
        algorithm.firstExecAL(userData, DateUtil.getDateZeroTime2bit(DateUtil.getStringToDate(lastPeriodDateValue + " 12:00:00")));
        JSONArray jsonArrayCycleDatas = algorithm.getCycleOutputJson();
        JSONArray jsonArrayUserDatas = algorithm.getDayOutputJson();
        JSONObject jsonObjectUserData = algorithm.getUserInfoJson();
        UploadCycleData(jsonArrayCycleDatas, jsonArrayUserDatas, jsonObjectUserData);
    }

    private void showProgressDialog() {
        progressDialog = new ProgressDialog(this.getActivity());
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(getString(R.string.data_in_process));
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    private void UploadCycleData(final JSONArray jsonArrayCycleDatas, final JSONArray jsonArrayUserDatas, final JSONObject jsonObjectUserData) {

        OKHttpUtil okHttpClient = new OKHttpUtil(this.getActivity());
        String appendUrl = "cycle/replaceCycle.json";
        try {
            AppLog.i("cycleData = " + jsonArrayCycleDatas.toString());
            AppLog.i("userData = " + jsonArrayUserDatas.toString());
            AppLog.i("userInfo = " + jsonObjectUserData.toString());
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("cycleData", jsonArrayCycleDatas);
            okHttpClient.add("userData", jsonArrayUserDatas);
            okHttpClient.add("userInfo", jsonObjectUserData);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    saveALResult2Sqlite(0);
                    initDayUnitDSOutputsListIntoMemory();
                    sendInitCalendarMsg();

                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        String str = response.body().string();
                        AppLog.i("cycle/replaceCycle response:" + str);
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");

                        if (200 == respCode) {
                            saveALResult2Sqlite(1);
                            initDayUnitDSOutputsListIntoMemory();
                            sendInitCalendarMsg();//通知日历更新
                            EventBus.getDefault().post(new CurveMsg());//通知画图更新
                            AppLog.i("UploadCycleData onResponse success!");
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            UploadCycleData(jsonArrayCycleDatas, jsonArrayUserDatas, jsonObjectUserData);
                        } else if(respCode == 215){
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                                progressDialog = null;
                            }
                        }else {
                            saveALResult2Sqlite(0);
                            initDayUnitDSOutputsListIntoMemory();
                            sendInitCalendarMsg();
                            AppLog.i("UploadCycleData onResponse failed! respCode = " + respCode);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        saveALResult2Sqlite(0);
                        initDayUnitDSOutputsListIntoMemory();
                        sendInitCalendarMsg();
                    }
                }
            });
        } catch (JSONException e) {
            AppLog.i("UploadCycleData JSONException!");
            e.printStackTrace();
            saveALResult2Sqlite(0);
            initDayUnitDSOutputsListIntoMemory();
            sendInitCalendarMsg();

        }

    }

    private void saveALResult2Sqlite(int isSynced) {
        algorithm.saveALData2Sqlite(isSynced);
    }

    private void initDayUnitDSOutputsListIntoMemory() {
        dbManager.initDayUnitDSOutputsList2Memory(App.userName);
    }

    private void sendInitCalendarMsg() {
        AlgoUpdateMsg algoUpdateMsg = new AlgoUpdateMsg();
        algoUpdateMsg.setRespCode(1);
        EventBus.getDefault().post(algoUpdateMsg);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        AppLog.i("LifeCycle get in HomeFragment onActivityCreated!");

        LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) fragmentHomeUpperLayout.getLayoutParams();
        upperHeight = linearParams.height;
        AppLog.i("upperHeight:" + upperHeight);
        showArticleList();
        //由于使用的是okHttp异步回调(即立即返回)，因此这里不能直接操作adapter, listview，因为此时网络
        //操作甚至还没得到结果返回，即articleBeanList这里为null。所以应该在onResponse回调里得到返回结果
        //之后，通过handler来同步UI线程的更新。

        setBBT();
        checkAppVersion();
    }

    private void checkAppVersion() {
        OKHttpUtil okHttpUtil = new OKHttpUtil(this.getActivity());
        final UpdateUtil updateUtil = new UpdateUtil(this.getContext());

        String appendUrl = "product/getNewVersionInfo.json?OSType=Android&DevType=" + updateUtil.getDevType();

        okHttpUtil.getAsync(appendUrl, okHttpUtil.new BaseCallBack() {
            @Override
            public void onFailure(Request request, IOException e) {
                super.onFailure(request, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {

                try {
                    JSONObject respJSONObj = new JSONObject(response.body().string());
                    int respCode = respJSONObj.getInt("code");

                    if (200 == respCode) {
                        AppLog.i("start compare version!");
                        int serverVersionCode = respJSONObj.getInt("versionCode");
                        int localVersionCode = updateUtil.getVerCode();
                        AppLog.i("localVersionCode = " + localVersionCode + ", serverVersionCode = " + serverVersionCode);

                        if (localVersionCode < serverVersionCode) {
                            AppLog.i("found new version! localVersionName = " + updateUtil.getVerName() + ", serverVersionName = " + respJSONObj.getString("version"));

                            String updateBaseURL = respJSONObj.getString("updateURL");
                            String updateURL = updateBaseURL + UpdateUtil.getChannelAPKName(getActivity());

                            AppLog.i("updateURL = " + updateURL);

                            String updateList = respJSONObj.getString("updates");

                            FoundNewVersionMsg foundNewVersionMsg = new FoundNewVersionMsg();
                            foundNewVersionMsg.setDownloadURL(updateURL);
                            foundNewVersionMsg.setUpdateList(updateList);
                            AppLog.i("updateURL = " + updateURL + ", updateList = " + updateList);

                            EventBus.getDefault().post(foundNewVersionMsg);
                        }
                    } else {
                        AppLog.i("checkAppVersion onResponse respCode failed! is:" + respCode);
                    }
                } catch (JSONException e) {
                    AppLog.i("checkAppVersion onResponse failed! JSONException!");
                    e.printStackTrace();
                }
            }
        });
    }

    @Subcriber
    private void foundNewAppVersion(FoundNewVersionMsg foundNewVersionMsg) {

        final String downloadURL = foundNewVersionMsg.getDownloadURL();
        String updateList = foundNewVersionMsg.getUpdateList();

        String formatUpdateList = getFormatUpdateList(updateList);

        String updateAlertTitle = getString(R.string.updateAlertTitle);
        String updateAlertMsg = getString(R.string.updateAlertMsg);
        String updateAlertPositiveButtonTxt = getString(R.string.updateAlertPositiveButtonTxt);
        String updateAlertNegativeButtonTxt = getString(R.string.updateAlertNegativeButtonTxt);

        Dialog dialog = new AlertDialog.Builder(getContext()).setTitle(updateAlertTitle)
                .setMessage(updateAlertMsg + formatUpdateList)
                .setCancelable(false)
                .setPositiveButton(updateAlertPositiveButtonTxt, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        downloadAPK(downloadURL);
                    }
                })
                .setNegativeButton(updateAlertNegativeButtonTxt, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }

    private String getFormatUpdateList(String updateList) {

        AppLog.i("new version updateList = " + updateList);

        String formatUpdateList = "\n";
        try {
            JSONArray updateListJSONArray = new JSONArray(updateList);

            for (int i = 0; i < updateListJSONArray.length(); i++) {
                JSONObject updateJSONObj = (JSONObject) updateListJSONArray.get(i);
                formatUpdateList += updateJSONObj.getString("update") + "\n";
            }

        } catch (JSONException e) {
            AppLog.i("JSONException e = " + e.getMessage());
        }

        return formatUpdateList;
    }

    private void downloadAPK(String downloadURL) {
        AppLog.i("start downloading apk from url = " + downloadURL);
        Intent intent = new Intent(getActivity(), DownloadService.class);
        intent.putExtra("downloadURL", downloadURL);
        getActivity().startService(intent);
    }


    /**
     * 初始化任务数量显示
     */

    private void taskInfo() {
        taskBBT.setVisibility(View.VISIBLE);
        taskWater.setVisibility(View.GONE);
        taskMedicine.setVisibility(View.GONE);
        taskSport.setVisibility(View.GONE);
        taskFruit.setVisibility(View.GONE);
        taskMucus.setVisibility(View.GONE);
        taskLHPaper.setVisibility(View.GONE);
        taskBUltrasonic.setVisibility(View.GONE);

        String taskIDs = dbManager.getSqliteKeyValue(App.userName, "taskIDs");
        if (null == taskIDs)
            taskIDs = "1,2,3";

        String[] taskIDsList = taskIDs.split(",");
        for (int i = 0; i < taskIDsList.length; i++) {
            if (Integer.parseInt(taskIDsList[i]) == 2) {
                taskWater.setVisibility(View.VISIBLE);
            } else if (Integer.parseInt(taskIDsList[i]) == 3) {
                taskMedicine.setVisibility(View.VISIBLE);
            } else if (Integer.parseInt(taskIDsList[i]) == 4) {
                taskSport.setVisibility(View.VISIBLE);
            } else if (Integer.parseInt(taskIDsList[i]) == 5) {
                taskFruit.setVisibility(View.VISIBLE);
            } else if (Integer.parseInt(taskIDsList[i]) == 6) {
                taskMucus.setVisibility(View.VISIBLE);
            } else if (Integer.parseInt(taskIDsList[i]) == 7) {
                taskLHPaper.setVisibility(View.VISIBLE);
            } else if (Integer.parseInt(taskIDsList[i]) == 8) {
                taskBUltrasonic.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 初始化已完成的任务
     */
    private void taskSelectInfo(String selectDate) {
        String taskIDs = dbManager.getSelectedTaskIds(selectDate);
        changeTaskForDate();
        if (null != taskIDs && 0 != taskIDs.length()) {
            String[] taskIDsList = taskIDs.split(",");
            for (int i = 0; i < taskIDsList.length; i++) {
                if (Integer.parseInt(taskIDsList[i]) == 1) {
                    setListBar(taskBBT, taskBBTBgColor, taskBBTBottomLineColor);
                } else if (Integer.parseInt(taskIDsList[i]) == 2) {
                    setListBar(taskWater, taskWaterBgColor, taskWaterBottomLineColor);
                } else if (Integer.parseInt(taskIDsList[i]) == 3) {
                    setListBar(taskMedicine, taskMedicineBgColor, taskMedicineBottomLineColor);
                } else if (Integer.parseInt(taskIDsList[i]) == 4) {
                    setListBar(taskSport, taskSportBgColor, taskSportBottomLineColor);
                } else if (Integer.parseInt(taskIDsList[i]) == 5) {
                    setListBar(taskFruit, taskFruitBgColor, taskFruitBottomLineColor);
                } else if (Integer.parseInt(taskIDsList[i]) == 6) {
                    setListBar(taskMucus, taskMucusBgColor, taskMucusBottomLineColor);
                } else if (Integer.parseInt(taskIDsList[i]) == 7) {
                    setListBar(taskLHPaper, taskLHPaperBgColor, taskLHPaperBottomLineColor);
                } else if (Integer.parseInt(taskIDsList[i]) == 8) {
                    setListBar(taskBUltrasonic, taskBUltrasonicBgColor, taskBUltrasonicBottomLineColor);
                }
            }
        }
    }

    private void changeTaskForDate() {
        taskBBT.setSelected(false);
        taskBBT.setBackgroundColor(getResources().getColor(R.color.article_gray));
        taskBBT.setBottomLineColor(getResources().getColor(R.color.black_overlay));

        taskWater.setSelected(false);
        taskWater.setBackgroundColor(getResources().getColor(R.color.article_gray));
        taskWater.setBottomLineColor(getResources().getColor(R.color.black_overlay));

        taskMedicine.setSelected(false);
        taskMedicine.setBackgroundColor(getResources().getColor(R.color.article_gray));
        taskMedicine.setBottomLineColor(getResources().getColor(R.color.black_overlay));

        taskSport.setSelected(false);
        taskSport.setBackgroundColor(getResources().getColor(R.color.article_gray));
        taskSport.setBottomLineColor(getResources().getColor(R.color.black_overlay));

        taskFruit.setSelected(false);
        taskFruit.setBackgroundColor(getResources().getColor(R.color.article_gray));
        taskFruit.setBottomLineColor(getResources().getColor(R.color.black_overlay));

        taskMucus.setSelected(false);
        taskMucus.setBackgroundColor(getResources().getColor(R.color.article_gray));
        taskMucus.setBottomLineColor(getResources().getColor(R.color.black_overlay));

        taskLHPaper.setSelected(false);
        taskLHPaper.setBackgroundColor(getResources().getColor(R.color.article_gray));
        taskLHPaper.setBottomLineColor(getResources().getColor(R.color.black_overlay));

        taskBUltrasonic.setSelected(false);
        taskBUltrasonic.setBackgroundColor(getResources().getColor(R.color.article_gray));
        taskBUltrasonic.setBottomLineColor(getResources().getColor(R.color.black_overlay));

        taskTitleBottomLine.setBackgroundColor(getResources().getColor(R.color.black_overlay));
    }

    /**
     * topbar选择日期
     *
     * @param oneDay
     */
    private void changeTopBarDate(int oneDay) {
        try {
            topbarDate = dateUtil.getSimpleDateAddOrMinus(topBar.getText(), oneDay);
            taskSelectInfo(topbarDate);
            topBar.setText(dateUtil.getDateAddOrMinus(topBar.getText(), oneDay));
            dateRecord = topBar.getText().split(" ")[0];
            MainActivity.chosedDateCalendar = dateRecord;
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.connectionStateLayout:
                AppLog.i("tabLayoutLeft clicked!");
                break;
            case R.id.recordLayout:
                RecordInfo recordInfo = new RecordInfo();
                recordInfo.setDate(topBar.getText().toString());
                EventBus.getDefault().post(recordInfo);

                //mAViewPager = (ViewPager) getActivity().findViewById(R.id.viewpager);
                break;
            case R.id.connectionStateText:
                if (connectionStateText.getText().toString().trim().equals(getString(R.string.not_paired))) {
                    Intent bindIntent = new Intent(getActivity(), MyDeviceChooseActivity.class);
                    bindIntent.putExtra("type", "bindThermometer");
                    startActivity(bindIntent);
                }
                break;
            case R.id.addTask:
                Intent intent = new Intent(getActivity(), ModifyTaskListActivity.class);
                startActivityForResult(intent, 0);
//                startActivity(intent);
                break;
            case R.id.taskBBT:
                setListBarAndUpload(taskBBT, taskBBTBgColor, taskBBTBottomLineColor, 1);
                break;
            case R.id.taskWater:
                setListBarAndUpload(taskWater, taskWaterBgColor, taskWaterBottomLineColor, 2);
                break;
            case R.id.taskMedicine:
                setListBarAndUpload(taskMedicine, taskMedicineBgColor, taskMedicineBottomLineColor, 3);
                break;
            case R.id.taskSport:
                setListBarAndUpload(taskSport, taskSportBgColor, taskSportBottomLineColor, 4);
                break;
            case R.id.taskFruit:
                setListBarAndUpload(taskFruit, taskFruitBgColor, taskFruitBottomLineColor, 5);
                break;
            case R.id.taskMucus:
                setListBarAndUpload(taskMucus, taskMucusBgColor, taskMucusBottomLineColor, 6);
                break;
            case R.id.taskLHPaper:
                setListBarAndUpload(taskLHPaper, taskLHPaperBgColor, taskLHPaperBottomLineColor, 7);
                break;
            case R.id.taskBUltrasonic:
                setListBarAndUpload(taskBUltrasonic, taskBUltrasonicBgColor, taskBUltrasonicBottomLineColor, 8);
                break;
            default:
                break;
        }
    }

    /**
     * 设置task颜色，并上传
     *
     * @param listBar
     * @param bgColor
     * @param bottomLineColor
     */
    private void setListBarAndUpload(ListBar listBar, int bgColor, int bottomLineColor, int taskId) {

        listBar.setSelected(!listBar.isSelected());

        if (listBar.isSelected()) {
            listBar.setBackgroundColor(getResources().getColor(bgColor));
            listBar.setBottomLineColor(getResources().getColor(bottomLineColor));

            if (topBar.getText().equals(dateUtil.getDateTopBar())) {
                postInTaskIDs(taskId, dateUtil.getSimpleDate() + " 12:00:00", 0);
            } else {
                postInTaskIDs(taskId, topbarDate + " 12:00:00", 0);
            }

            anyTaskSelected++;
        } else {
            listBar.setBackgroundColor(getResources().getColor(R.color.article_gray));
            listBar.setBottomLineColor(getResources().getColor(R.color.black_overlay));

            if (topBar.getText().equals(dateUtil.getDateTopBar())) {
                postInTaskIDs(taskId, dateUtil.getSimpleDate() + " 12:00:00", 1);
            } else {
                postInTaskIDs(taskId, topbarDate + " 12:00:00", 1);
            }

            anyTaskSelected--;
        }

        if (anyTaskSelected > 0) {
            taskTitleBottomLine.setBackgroundColor(getResources().getColor(R.color.task_selected_line_color));
        } else {
            addTask.setSelected(false);
            taskTitleBottomLine.setBackgroundColor(getResources().getColor(R.color.black_overlay));
        }
    }

    /**
     * 设置task颜色
     *
     * @param listBar
     * @param bgColor
     * @param bottomLineColor
     */
    private void setListBar(ListBar listBar, int bgColor, int bottomLineColor) {

        listBar.setSelected(!listBar.isSelected());

        if (listBar.isSelected()) {
            listBar.setBackgroundColor(getResources().getColor(bgColor));
            listBar.setBottomLineColor(getResources().getColor(bottomLineColor));

//            postInTaskIDs(taskId, dateUtil.getDate(), 0);

            anyTaskSelected++;
        } else {
            listBar.getBackground().setAlpha(0);
            listBar.setBottomLineColor(getResources().getColor(R.color.black_overlay));

//            postInTaskIDs(taskId, dateUtil.getDate(), 0);

            anyTaskSelected--;
        }

        if (anyTaskSelected > 0) {
            taskTitleBottomLine.setBackgroundColor(getResources().getColor(R.color.task_selected_line_color));
        } else {
            addTask.setSelected(false);
            taskTitleBottomLine.setBackgroundColor(getResources().getColor(R.color.black_overlay));
        }
    }

    private void postInTaskIDs(final int taskID, final String completeDate, final int taskDelete) {
        if (InternetUtil.hasInternet()) {
            SyncCompleteTaskMsg syncCompleteTaskMsg = new SyncCompleteTaskMsg();
            syncCompleteTaskMsg.setTaskID(taskID);
            syncCompleteTaskMsg.setTaskType(1);
            syncCompleteTaskMsg.setCompleteDate(completeDate);
            syncCompleteTaskMsg.setTaskDelete(taskDelete);
            SyncCompleteTask syncCompleteTask = new SyncCompleteTask(getContext(), syncCompleteTaskMsg);
            syncCompleteTask.syncCompleteTaskWithNetwork();
        } else {
            tasksUtil.setTaskID(taskID);
            tasksUtil.setCompleteDate(completeDate);
            tasksUtil.setTaskDelete(taskDelete);
            sendNOKResp(tasksUtil);
            Toast.makeText(getContext(), getString(R.string.network_anomalies_wait), Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 上传完成taskID
     */
    private void postInTaskIDs(final TasksUtil tasksUtil) {

        String appendUrl = "task/addOrUpdateComplete.json";
        OKHttpUtil okHttpClient = new OKHttpUtil(HomeFragment.this.getActivity());
        JSONArray tasksListJsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("taskID", tasksUtil.getTaskID());
            jsonObject.put("taskType", 1);
            jsonObject.put("completeDate", tasksUtil.getCompleteDate());
            jsonObject.put("taskDelete", tasksUtil.getTaskDelete());
            tasksListJsonArray.put(jsonObject);

            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("comTasks", tasksListJsonArray);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    sendNOKResp(tasksUtil);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());

                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            sendOKResp(tasksUtil);
                            AppLog.i("insert task ids onResponse success!");
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            postInTaskIDs(tasksUtil);
                        } else {
                            sendNOKResp(tasksUtil);
                            AppLog.i("insert task ids onResponse respCode failed! is:" + respCode);
                        }
                    } catch (JSONException e) {
                        AppLog.i("insert task ids onResponse failed!");
                        sendNOKResp(tasksUtil);
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            sendNOKResp(tasksUtil);
            e.printStackTrace();
        }
    }

    @Subcriber
    private void syncCompleteTask(SyncCompleteTaskMsg syncCompleteTaskMsg) {
        tasksUtil.setTaskID(syncCompleteTaskMsg.getTaskID());
        tasksUtil.setCompleteDate(syncCompleteTaskMsg.getCompleteDate());
        tasksUtil.setTaskDelete(syncCompleteTaskMsg.getTaskDelete());
        postInTaskIDs(tasksUtil);
    }

    private void sendOKResp(TasksUtil tasksUtil) {
        tasksUtil.setCode(INSERT_TASK_OK);
        tasksUtil.setIsSynced(1);
        EventBus.getDefault().post(tasksUtil);
    }

    private void sendNOKResp(TasksUtil tasksUtil) {
        tasksUtil.setCode(INSERT_TASK_NOK);
        tasksUtil.setIsSynced(0);
        EventBus.getDefault().post(tasksUtil);
    }

    @Subcriber
    private void taskIDs(TasksUtil tasksUtil) {
        switch (tasksUtil.getCode()) {
            case INSERT_TASK_OK:
                AppLog.i("update task ids onResponse success!");
                completeTask2DB(tasksUtil);
                break;
            case INSERT_TASK_NOK:
                //网络请求失败，仍然添加到本地sqlite数据库
                AppLog.i("update task ids onResponse failed!");
                completeTask2DB(tasksUtil);
                break;
        }
    }

    public void completeTask2DB(TasksUtil tasksUtil) {
        dbManager.updateUserCompleteTaskID(App.userName, tasksUtil.getCompleteDate(), tasksUtil.getTaskID(), tasksUtil.getTaskDelete(), tasksUtil.getIsSynced());
    }

    @Subcriber
    public void onCurveMsg(CurveMsg curveMsg) {
        setBBT();
    }

    private void setBBT() {
        UserRecordData userRecordData = new UserRecordData(getActivity(), DateUtil.getStringToDate(dateRecord + " 00:00:00"), App.userName);
        int mensesValue = getMensesState(DateUtil.getStringToDate(dateRecord + " 12:00:00"));
        int mucusStatus = userRecordData.getMucusStatus();
        UserTemperatureInfo userTemperatureInfo = dbManager.getSelectedDayBBTTemperature(App.userName, dateRecord);
        if (null != userTemperatureInfo || (mensesValue != 0) || mucusStatus > 0) {
            bbtView.setVisibility(View.VISIBLE);
            if (null != userTemperatureInfo) {
                bbtIcon.setVisibility(View.VISIBLE);
                bbtText.setVisibility(View.VISIBLE);
                bbtText.setText(getString(R.string.bbt) + userTemperatureInfo.getTemperature() + "℃");

            } else {
                bbtIcon.setVisibility(View.GONE);
                bbtText.setVisibility(View.GONE);
            }
            if (mucusStatus > 0) {
                mensesOrMucusIcon.setVisibility(View.VISIBLE);
                mensesOrMucusText.setVisibility(View.VISIBLE);
                mensesOrMucusIcon.setBackground(getResources().getDrawable(R.drawable.record_mucus_icon));
                mensesOrMucusText.setText(getString(R.string.record_mucus_icon_name) + "：" + RecordFragmentCommonList.mucusStatus[mucusStatus - 1]);
            } else {
                if (mensesValue != 0) {
                    mensesOrMucusIcon.setVisibility(View.VISIBLE);
                    mensesOrMucusText.setVisibility(View.VISIBLE);
                    if(mensesValue == 1){
                        mensesOrMucusIcon.setBackground(getResources().getDrawable(R.drawable.record_menses_icon));
                        mensesOrMucusText.setText(getString(R.string.menstruation_bleeding));
                    }else{
                        mensesOrMucusIcon.setBackground(getResources().getDrawable(R.drawable.record_menses_icon));
                        mensesOrMucusText.setText(getString(R.string.menstruation_bleeding_away));
                    }

                } else {
                    mensesOrMucusIcon.setVisibility(View.GONE);
                    mensesOrMucusText.setVisibility(View.GONE);
                }
            }

            LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) fragmentHomeUpperLayout.getLayoutParams();
            linearParams.height = upperHeight + 100;
            fragmentHomeUpperLayout.setLayoutParams(linearParams);
        } else {
            LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) fragmentHomeUpperLayout.getLayoutParams();
            linearParams.height = upperHeight;
            fragmentHomeUpperLayout.setLayoutParams(linearParams);
            bbtView.setVisibility(View.GONE);
        }
    }

    private int getMensesState(long dateStamp){
        int result = 0;
        long currentRecordTime = dateStamp;
        if(null == App.DayUnitDSOutputMap.get(currentRecordTime)){
            AppLog.e("App.DayUnitDSOutputMap.get(currentRecordTime) is NULL, " +
                    "currentRecordTime:" + currentRecordTime);
            return 0;
        }

        if(App.DayUnitDSOutputMap.get(currentRecordTime).periodAchieveConfirm == 0 && App.DayUnitDSOutputMap.get(currentRecordTime).periodAchieveForecast == 0 ){
            return 0;
        }
        List<DayUnitDSOutput> dayOutputList = new ArrayList<>();
        boolean isHaveStartMenses = false;
        for(int i =  14; i >= 0; i--){
            if(null != App.DayUnitDSOutputMap.get(currentRecordTime - i * (24 * 3600))){
                dayOutputList.add(App.DayUnitDSOutputMap.get(currentRecordTime - i * (24 * 3600)));

                if(App.DayUnitDSOutputMap.get(currentRecordTime - i * (24 * 3600)).homePageNextMenstruation == 1)
                    isHaveStartMenses = true;
            }
        }

        if(dayOutputList.size() >= 10){
            if(isHaveStartMenses){
                if(dayOutputList.get(dayOutputList.size() - 2).homePageNextMenstruation == 1){
                    if(App.DayUnitDSOutputMap.get(currentRecordTime).periodAchieveConfirm >0){
                        return  1;
                    }else{
                        return  0;
                    }
                }

                if(App.DayUnitDSOutputMap.get(currentRecordTime).homePageNextMenstruation == 1){
                    return  0;
                }else{
                    boolean haveConfirmPS = false;
                    for(DayUnitDSOutput dayUnitDSOutput : dayOutputList){
                        if(dayUnitDSOutput.periodAchieveConfirm > 0){
                            haveConfirmPS = true;
                            break;
                        }
                    }
                    if(haveConfirmPS == false){
                        return  0;
                    }else{
                        if(App.DayUnitDSOutputMap.get(currentRecordTime).periodAchieveForecast > 0){
                            //设置确认的经期
                            //mensesBlood = 1;
                        }
                        if(App.DayUnitDSOutputMap.get(currentRecordTime).homePageMenstruationEnd == 0){
                            return  2;
                        }else {
                            return  0;
                        }
                    }
                }
            }else{
                return  0;
            }

        }else{
            return  0;
        }

    }

    private String setTask() {
        String taskIDsSelected = "";

        if (taskBBT.isSelected()) {
            taskIDsSelected = taskIDsSelected + "1";
        }

        if (taskWater.isSelected()) {
            taskIDsSelected = taskIDsSelected + ",2";
        }

        if (taskMedicine.isSelected()) {
            taskIDsSelected = taskIDsSelected + ",3";
        }

        if (taskSport.isSelected()) {
            taskIDsSelected = taskIDsSelected + ",4";
        }

        if (taskFruit.isSelected()) {
            taskIDsSelected = taskIDsSelected + ",5";
        }

        if (taskMucus.isSelected()) {
            taskIDsSelected = taskIDsSelected + ",6";
        }

        if (taskLHPaper.isSelected()) {
            taskIDsSelected = taskIDsSelected + ",7";
        }

        if (taskBUltrasonic.isSelected()) {
            taskIDsSelected = taskIDsSelected + ",8";
        }

        if (taskIDsSelected.length() > 0) {
            if (taskIDsSelected.substring(0, 1).equals(",")) {
                taskIDsSelected = taskIDsSelected.substring(1);
            }
        }

        return taskIDsSelected;
    }

    @Override
    public void rightButtonClick(ListBar listBar) {
        AppLog.i("rightButtonClick  " + listBar.getId());
        switch (listBar.getId()) {
            case R.id.taskBBT:
                setListBarAndUpload(taskBBT, taskBBTBgColor, taskBBTBottomLineColor, 1);
                break;
            case R.id.taskWater:
                setListBarAndUpload(taskWater, taskWaterBgColor, taskWaterBottomLineColor, 2);
                break;
            case R.id.taskMedicine:
                setListBarAndUpload(taskMedicine, taskMedicineBgColor, taskMedicineBottomLineColor, 3);
                break;
            case R.id.taskSport:
                setListBarAndUpload(taskSport, taskSportBgColor, taskSportBottomLineColor, 4);
                break;
            case R.id.taskFruit:
                setListBarAndUpload(taskFruit, taskFruitBgColor, taskFruitBottomLineColor, 5);
                break;
            case R.id.taskMucus:
                setListBarAndUpload(taskMucus, taskMucusBgColor, taskMucusBottomLineColor, 6);
                break;
            case R.id.taskLHPaper:
                setListBarAndUpload(taskLHPaper, taskLHPaperBgColor, taskLHPaperBottomLineColor, 7);
                break;
            case R.id.taskBUltrasonic:
                setListBarAndUpload(taskBUltrasonic, taskBUltrasonicBgColor, taskBUltrasonicBottomLineColor, 8);
                break;
            default:
                break;
        }
    }


    private void showArticleList() {
        if (InternetUtil.hasInternet())
            showArticleListFromNetwork();
        else
            showArticleListFromCache();
    }

    /**
     * 获取推荐文章
     */
    private void showArticleListFromNetwork() {
        OKHttpUtil okHttpUtil = new OKHttpUtil(this.getActivity());
        String appendUrl = "recomda/getRandomRecomdations.json";

        try {
            okHttpUtil.add("userType", String.valueOf(App.status));
            okHttpUtil.add("counter", String.valueOf(RETRIEVE_ARTICLE_COUNT));
            okHttpUtil.postAsync(appendUrl, okHttpUtil.new BaseCallBack() {
                @Override
                public void onFailure(Request request, IOException e) {
                    sendResp2Hanlder(RETRIEVE_ARTICLE_LIST_NOK);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    AppLog.i("okHttpUtil.getAsync success!");
                    articleBeanList = getArticleBeanListFromResp(response.body().string());
                    sendResp2Hanlder(RETRIEVE_ARTICLE_LIST_OK);
                }

            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查文章是否已被收藏
     */
    private void checkArticleIsCollected() {
        try {
            List<CollectionBean> collectionBeanList = dbManager.getCollectionArticles(App.userName);

            for (int i = 0; i < articleBeanList.size(); i++) {
                int articleId = articleBeanList.get(i).getArticleId();
                boolean isCollected = isArticleCollected(collectionBeanList, articleId);
                articleBeanList.get(i).setIsCollected(isCollected);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private boolean isArticleCollected(List<CollectionBean> collectionBeanList, int articleId) {
        boolean isCollected = false;

        if (collectionBeanList == null || collectionBeanList.size() == 0)
            isCollected = false;
        else {
            for (CollectionBean collectionBean : collectionBeanList) {
                if (collectionBean.getArticleId() == articleId) {
                    isCollected = true;
                    break;
                }
            }
        }

        return isCollected;
    }

    @Subcriber
    private void dealBatteryVolumeMsg(BatteryVolumeMsg batteryVolumeMsg) {

        setBatteryVolumeImage(batteryVolumeMsg.getRespCode());

    }

    public void setBatteryVolumeImage(int n) {
        if (n == 0)
            connectionStateImg.setImageResource(R.drawable.home_upper_tab_left_binded_unconnected);
        if (n == 1) connectionStateImg.setImageResource(R.drawable.battery_power_1);
        if (n == 2) connectionStateImg.setImageResource(R.drawable.battery_power_2);
        if (n == 3) connectionStateImg.setImageResource(R.drawable.battery_power_3);
        if (n == 4) connectionStateImg.setImageResource(R.drawable.battery_power_4);
        if (n == 5) connectionStateImg.setImageResource(R.drawable.battery_power_5);
    }

    private void showArticleListFromCache() {
        articleBeanList = getArticleBeanListFromCache();
        realShowArticleList();
    }

    private void sendResp2Hanlder(int flag) {
        Message respMessage = Message.obtain();
        respMessage.what = flag;
        mHandler.sendMessage(respMessage);
    }

    /**
     * 获取文章列表，并封装为list集合
     *
     * @param response
     * @return
     * @throws IOException
     */
    private List<ArticleBean> getArticleBeanListFromResp(String response) throws IOException {
        List<ArticleBean> articleBeans = null;
        AppLog.i("getArticleBeanListFromResp! response = " + response);

        try {
            JSONObject respJSONObj = new JSONObject(response);

            int respCode = respJSONObj.getInt("code");
            AppLog.i("home fragment article list respCode = " + respCode);

            if (200 == respCode) {
                JSONArray articleJSONArray = respJSONObj.getJSONArray("forums");
                articleBeans = new ArrayList<ArticleBean>();
                for (int i = 0; i < articleJSONArray.length(); i++) {
                    JSONObject articleJSONObj = articleJSONArray.getJSONObject(i);
                    int articleId = articleJSONObj.getInt("forumID");
                    String articleImageName = articleJSONObj.getString("imgName");
                    String articleTitle = articleJSONObj.getString("title");
                    String articleDate = articleJSONObj.getString("date");
                    int articleRead = articleJSONObj.getInt("read");

                    ArticleBean articleBean = new ArticleBean();
                    articleBean.setArticleId(articleId);
                    articleBean.setImageUrl(App.articleImageBaseUrlPath + articleImageName);
                    articleBean.setTitle(articleTitle);
                    articleBean.setDate(articleDate);
                    articleBean.setRead(articleRead);

                    articleBeans.add(articleBean);
                }
            } else {
                AppLog.e("fragment article list get error response Code!");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return articleBeans;
    }

    /**
     * 获取用户收藏列表，并封装为list集合
     *
     * @param response
     * @return
     * @throws IOException
     */
    private List<ArticleBean> getIsCollectedBeanListFromResp(String response) throws IOException {
        List<ArticleBean> articleIsCollectedBeans = null;
        AppLog.i("getIsCollectedBeanListFromResp! response = " + response);

        try {
            JSONObject respJSONObj = new JSONObject(response);
            int respCode = respJSONObj.getInt("code");
            if (App.HTTP_RESP_OK == respCode) {
                JSONArray articleJSONArray = respJSONObj.getJSONArray("collections");
                articleIsCollectedBeans = new ArrayList<ArticleBean>();
                for (int i = 0; i < articleJSONArray.length(); i++) {
                    JSONObject articleJSONObj = articleJSONArray.getJSONObject(i);
                    String isCollectedId = articleJSONObj.getString("collectionURL");
                    ArticleBean articleBean = new ArticleBean();
                    articleBean.setCollectedId(isCollectedId);

                    articleIsCollectedBeans.add(articleBean);
                }
            } else {
                AppLog.e("fragment article list get error response Code!");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return articleIsCollectedBeans;
    }

    private Handler mHandler = new ArticleListHandler();

    boolean mIsShowBack;

    @Override
    public void click(final View v) {

        if ((v.getTag() + "").equals(adapter.getPrimaryItemPostion() + "")) {
            mRightOutSet = (AnimatorSet) AnimatorInflater.loadAnimator(getContext(), R.animator.anim_out);
            mLeftInSet = (AnimatorSet) AnimatorInflater.loadAnimator(getContext(), R.animator.anim_in);

            final FrameLayout mFlContainer = (FrameLayout) adapter.getPrimaryItem().findViewById(R.id.main_fl_container);
            final FrameLayout mFlCardBack = (FrameLayout) adapter.getPrimaryItem().findViewById(R.id.main_fl_card_back);
            final FrameLayout mFlCardFront = (FrameLayout) adapter.getPrimaryItem().findViewById(R.id.main_fl_card_front);

            mRightOutSet.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationStart(Animator animation) {
                    super.onAnimationStart(animation);
                    mFlContainer.setClickable(false);
                }
            });
            mLeftInSet.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    mFlContainer.setClickable(true);
                }
            });
            int distance = 16000;
            float scale = getContext().getResources().getDisplayMetrics().density * distance;
            mFlCardFront.setCameraDistance(scale);
            mFlCardBack.setCameraDistance(scale);
            v.setClickable(false);


            if (mLastPosition != adapter.getPrimaryItemPostion()) {
                mIsShowBack = false;
//                Toast.makeText(getContext(), "AAAA", Toast.LENGTH_SHORT).show();
            }

            if (!mIsShowBack) {
                mRightOutSet.setTarget(mFlCardBack);
                mLeftInSet.setTarget(mFlCardFront);
                mRightOutSet.start();
                mLeftInSet.start();
                mIsShowBack = true;
            } else { // 背面朝上
                mRightOutSet.setTarget(mFlCardFront);
                mLeftInSet.setTarget(mFlCardBack);
                mRightOutSet.start();
                mLeftInSet.start();
                mIsShowBack = false;
            }
            mLastPosition = (int) v.getTag();
            new Thread() {
                @Override
                public void run() {
                    try {
                        for (int i = 0; i < 10; i++) {
                            Thread.sleep(3000);
                            v.setClickable(true);
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();


        }

    }


    private class ArticleListHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RETRIEVE_ARTICLE_LIST_OK:
                    checkArticleIsCollected();
                    realShowArticleList();
                    saveArticleListIntoCache();
                    break;
                case RETRIEVE_ARTICLE_LIST_NOK:
                    //Toast.makeText(getContext(), "获取文章列表失败!", Toast.LENGTH_SHORT).show();
                    showArticleListFromCache();
                    break;
            }
        }

    }

    private void realShowArticleList() {
        articleAdapter = new ArticleAdapter(getContext(), articleBeanList);
        articleListView.setAdapter(articleAdapter);
        setListViewHeight();
    }

    // ScrollView内部嵌套ListView的情况，必须给ListView设置高度，
    // 否则Adapter的getVew里取得的position每次都是0，因为底部已经没有空间放置viewItem。
    // 因此，设置ListView的高度为count个children的高度+分隔线。
    private void setListViewHeight() {
        if (articleBeanList == null || articleBeanList.size() == 0)
            return;

        int totalHeight = 0;
        for (int i = 0; i < articleBeanList.size(); i++) {
            View listItem = articleAdapter.getView(i, null, articleListView);

            //给listItem初始化宽高，否则会报空
            ViewGroup.LayoutParams layoutParams = listItem.getLayoutParams();
            if (layoutParams == null) {
                layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                listItem.setLayoutParams(layoutParams);
            }

            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = articleListView.getLayoutParams();
        params.height = totalHeight + (articleListView.getDividerHeight() * (articleListView.getCount() - 1));
        articleListView.setLayoutParams(params);
    }

    private void saveArticleListIntoCache() {
        // 如果有网络, 保存最新网络图片到本地ExternalCache缓存(命名为article1.jpg和article2.jpg ...),
        // 并保存关键字段到SharedPreference
        if (InternetUtil.hasInternet()) {
            try {
                new Thread() {
                    @Override
                    public void run() {
                        App.savePreference("article_count", articleBeanList.size());

                        for (int i = 0; i < articleBeanList.size(); i++) {
                            try {
                                String fileName = "article" + i + ".jpg";
                                SDCardHelper.saveImage2SDCardPrivateCacheDirFromNetwork(articleBeanList.get(i).getImageUrl(), fileName, getContext());

                                int articleId = articleBeanList.get(i).getArticleId();
                                String articleTitle = articleBeanList.get(i).getTitle();
                                String articleTime = articleBeanList.get(i).getDate();
                                boolean isCollected = articleBeanList.get(i).isCollected();

                                App.savePreference("article" + i + "_id", articleId);
                                App.savePreference("article" + i + "_title", articleTitle);
                                App.savePreference("article" + i + "_time", articleTime);
                                App.savePreference("article" + i + "_isCollected", isCollected);

                            } catch (Exception e) {
                                AppLog.i("saveArticleListIntoCache failed!" + e);
                                e.printStackTrace();
                            }
                        }
                    }
                }.start();
            } catch (Exception e) {
                AppLog.i("saveArticleListIntoCache failed!");
                e.printStackTrace();
            }
        }
    }

    private List<ArticleBean> getArticleBeanListFromCache() {
        AppLog.i("has no network access! getArticleBeanListFromCache!");

        List<ArticleBean> articleBeans = new ArrayList<ArticleBean>();

        int article_count = App.getPreferenceInt("article_count");
        for (int i = 0; i < article_count; i++) {

            int articleId = App.getPreferenceInt("article" + i + "_id");
            String fileName = "article" + i + ".jpg";
            String imgUrl = "file://" + getContext().getExternalCacheDir().getAbsolutePath() + "/" + fileName;
            String articleTitle = App.getPreference("article" + i + "_title");
            String articleDate = App.getPreference("article" + i + "_time");
            Boolean articleIsCollected = App.getPreferenceBoolean("article" + i + "_isCollected");

            ArticleBean articleBean = new ArticleBean();
            articleBean.setArticleId(articleId);
            articleBean.setImageUrl(imgUrl);
            articleBean.setTitle(articleTitle);
            articleBean.setDate(articleDate);
            articleBean.setIsCollected(articleIsCollected);

            articleBeans.add(articleBean);
        }

        return articleBeans;
    }

    public void temperatureAction(String tem, String time) {
        bbtText.setText(getString(R.string.bbt) + tem);
        bbtView.setVisibility(View.VISIBLE);
    }

    public void connectionStateTextAction(String text) {
        connectionStateText.setText(text);
    }

    @Subcriber
    private void connectStateAction(ConnectStateMsg connectStateMsg) {

        if (null != connectionStateText) {
            if (connectStateMsg.getRespCode() == 0) {
                connectionStateText.setText(getString(R.string.un_connection));
                setBatteryVolumeImage(0);
            }
            if (connectStateMsg.getRespCode() == 1) {
                connectionStateText.setText(getString(R.string.connected));
            }
            if (connectStateMsg.getRespCode() == 2) {
                connectionStateText.setText(getString(R.string.not_paired));
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case TASK_INFO:
                taskInfo();
                break;
            default:
                break;
        }
    }

    // 在收藏页面删除某篇文章，HomeFragment对应的推荐文章列表里若有此收藏文章，则更新其收藏状态
    @Subcriber
    private void setArticleCollectionStatus(DelCollectedArticle delCollectedArticle) {
        AppLog.i("intent to setArticleCollectionStatus! delCollectedArticle.articleId = " + delCollectedArticle.articleId);

        for (int i = 0; i < articleBeanList.size(); i++) {
            if (articleBeanList.get(i).getArticleId() == delCollectedArticle.articleId) {
                articleBeanList.get(i).setIsCollected(false);

                //articleAdapter = new ArticleAdapter(getActivity(), articleBeanList);
                //articleListView.setAdapter(articleAdapter);
                break;
            }
        }

        articleAdapter.notifyDataSetChanged();
    }


    private void initCalendar(View view) {
        list = new ArrayList<>();
        for (int i = 0; i < App.dayUnitDSOutputsList.size(); i++) {
            list.add(new Calendar(
                    DateUtil.getDateOnlyStr2bit2(App.dayUnitDSOutputsList.get(i).date),
                    getDayNumber(i),
                    getDayTitle(i),
                    getState(i),
                    getPercentNumber(i),
                    getPercentTitle(i)));

        }
        viewPager = (FlipViewPager) view.findViewById(R.id.flip_view_pager);
        adapter = new PageAdapter(getActivity(), list, this);
        viewPager.setOffscreenPageLimit(5);
        viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                setBBT();
            }

            @Override
            public void onPageSelected(int position) {
                statePosition = position;
                StatusBarUtil(position);
                if (isFromTop) {
                    changeTopBarDate(statePosition > adapter.getPrimaryItemPostion() ? ADD_ONE_DAY : MINUS_ONE_DAY);
//                    topBar.setText(dateUtil.getCircleCalendarTopDate(App.dayUnitDSOutputsList.get(position).date));
                }
                isFromTop = false;
                SpannableString topBars = new SpannableString(dateUtil.getCircleCalendarTopDate(App.dayUnitDSOutputsList.get(position).date));
                topBars.setSpan(new ForegroundColorSpan(getResources().getColor(getBGcolord(position))), 0, topBars.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                topBar.setText(topBars);
                dateRecord = topBar.getText().split(" ")[0];
                MainActivity.chosedDateCalendar = dateRecord;
                topbarDate = dateUtil.getSimpleCircleCalendarTopDate(App.dayUnitDSOutputsList.get(position).date);

                taskSelectInfo(topbarDate);

                setLinearBg(getState(position));

                if (DateUtil.getCurrentDay().equals(topbarDate)) {
                    topBar.setLeftButtonVisible(false);
                } else {
                    topBar.setLeftButtonVisible(true);
                }
                if (DateUtil.getStringToDateM(topbarDate) - DateUtil.getStringToDateM(DateUtil.getCurrentDay()) <= 0) {
                    SetTextStyleBefore();
                } else {
                    SetTextStyleAfter();
                }
//                StatusBarUtil.setColor(getActivity(), getResources().getColor(getBGcolord(position)), 0);
                App.savePreference(Constant.kStatusColor, getBGColor(position));
                App.savePreference(Constant.kStatusDay, topBar.getText());
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        int position = 0;
        for (int i = 0; i < App.dayUnitDSOutputsList.size(); i++) {
            if (dateUtil.getCircleCalendarDate().equals(dateUtil.getCircleCalendarDate2(App.dayUnitDSOutputsList.get(i).date))) {
                position = i;
            }
        }
        toToday(position);
    }

    private void StatusBarUtil(int i) {
        topBar.setBackgroundResource(getBGColor(i));
        StatusBarUtil.setColor(getActivity(), getResources().getColor(getBGColor(i)), 0);
    }

    private void setLinearBg(String state) {
        switch (Locale.getDefault().getLanguage()) {
            case "zh":
                switch (state) {
                    case Constant.kMenstruation:
                        if (App.dayUnitDSOutputsList.get(viewPager.getCurrentItem()).isConfrimOrForecast(App.status) == DayUnitDSOutput.PERIOD_CONFIRM_YJQ) {
                            recordLayout.setBackgroundResource(R.drawable.home_upper_tab_right_bg_pink);
                        } else {
                            recordLayout.setBackgroundResource(R.drawable.home_upper_tab_right_bg_pink_pre);
                        }
                        break;
                    case Constant.kFollicular_phase:
                        recordLayout.setBackgroundResource(R.drawable.home_upper_tab_right_bg_blue);
                        break;
                    case Constant.kLuteal:
                        recordLayout.setBackgroundResource(R.drawable.home_upper_tab_right_bg_yellow);
                        break;
                    case Constant.kSafe:
                        recordLayout.setBackgroundResource(R.drawable.home_upper_tab_right_bg_deep_green);
                        break;
                    case Constant.kDangerous:
                        recordLayout.setBackgroundResource(R.drawable.home_upper_tab_right_bg_red);
                        break;
                    default:
                        recordLayout.setBackgroundResource(R.drawable.home_upper_tab_right_bg_green);
                }
                break;
            default: {
                switch (state) {
                    case EnConstant.kMenstruation:
                        if (App.dayUnitDSOutputsList.get(viewPager.getCurrentItem()).isConfrimOrForecast(App.status) == DayUnitDSOutput.PERIOD_CONFIRM_YJQ) {
                            recordLayout.setBackgroundResource(R.drawable.home_upper_tab_right_bg_pink);
                        } else {
                            recordLayout.setBackgroundResource(R.drawable.home_upper_tab_right_bg_pink_pre);
                        }
                        break;
                    case EnConstant.kFollicular_phase:
                        recordLayout.setBackgroundResource(R.drawable.home_upper_tab_right_bg_blue);
                        break;
                    case EnConstant.kLuteal:
                        recordLayout.setBackgroundResource(R.drawable.home_upper_tab_right_bg_yellow);
                        break;
                    case EnConstant.kSafe:
                        recordLayout.setBackgroundResource(R.drawable.home_upper_tab_right_bg_deep_green);
                        break;
                    case EnConstant.kDangerous:
                        recordLayout.setBackgroundResource(R.drawable.home_upper_tab_right_bg_red);
                        break;
                    default:
                        recordLayout.setBackgroundResource(R.drawable.home_upper_tab_right_bg_green);
                }
            }
        }

    }

    private int getBGColor(int i) {
        switch (Locale.getDefault().getLanguage()) {
            case "zh":
                if (list.size() > 0) {
                    switch (list.get(i).getState() + "") {
                        case Constant.kMenstruation:
                            if (App.dayUnitDSOutputsList.get(i).isConfrimOrForecast(App.status) == DayUnitDSOutput.PERIOD_CONFIRM_YJQ) {
                                return R.color.circle_bg_pink;
                            }
                            return R.color.circle_bg_pink_pre;
                        case Constant.kFollicular_phase:
                            return R.color.circle_bg_blue;
                        case Constant.kLuteal:
                            return R.color.circle_bg_yellow;
                        case Constant.kSafe:
                            return R.color.circle_bg_blue;
                        case Constant.kDangerous:
                            return R.color.circle_bg_red;
                        default:
                            return R.color.circle_bg_green;
                    }
                } else {
                    return R.color.circle_bg_blue;
                }
            default:
                if (list.size() > 0) {
                    switch (list.get(i).getState()) {
                        case EnConstant.kMenstruation:
                            if (App.dayUnitDSOutputsList.get(i).isConfrimOrForecast(App.status) == DayUnitDSOutput.PERIOD_CONFIRM_YJQ) {
                                return R.color.circle_bg_pink;
                            }
                            return R.color.circle_bg_pink_pre;

                        case EnConstant.kFollicular_phase:
                            return R.color.circle_bg_blue;
                        case EnConstant.kLuteal:
                            return R.color.circle_bg_yellow;
                        case EnConstant.kSafe:
                            return R.color.circle_bg_blue;
                        case EnConstant.kDangerous:
                            return R.color.circle_bg_red;
                        default:
                            return R.color.circle_bg_green;
                    }
                } else {
                    return R.color.circle_bg_blue;
                }
        }

    }

    private int getBGcolord(int i) {
        switch (Locale.getDefault().getLanguage()) {
            case "zh":
                if (list.size() > 0) {
                    switch (list.get(i).getState() + "") {
                        case Constant.kMenstruation:
                            if (App.dayUnitDSOutputsList.get(i).isConfrimOrForecast(App.status) == DayUnitDSOutput.PERIOD_CONFIRM_YJQ) {

                                return R.color.circle_bg_pink_d;
                            }
                            return R.color.circle_bg_pink_d_pre;
                        case Constant.kFollicular_phase:
                            return R.color.circle_bg_blue_d;
                        case Constant.kLuteal:
                            return R.color.circle_bg_yellow_d;
                        case Constant.kSafe:
                            return R.color.circle_bg_blue_d;
                        case Constant.kDangerous:
                            return R.color.circle_bg_red_d;
                        default:
                            return R.color.circle_bg_green_d;
                    }
                } else {
                    return R.color.lpq_color;
                }

            default:
                if (list.size() > 0) {
                    switch (list.get(i).getState() + "") {
                        case EnConstant.kMenstruation:
                            if (App.dayUnitDSOutputsList.get(i).isConfrimOrForecast(App.status) == DayUnitDSOutput.PERIOD_CONFIRM_YJQ) {
                                return R.color.circle_bg_pink_d;
                            }
                            return R.color.circle_bg_pink_d_pre;

                        case EnConstant.kFollicular_phase:
                            return R.color.circle_bg_blue_d;
                        case EnConstant.kLuteal:
                            return R.color.circle_bg_yellow_d;
                        case EnConstant.kSafe:
                            return R.color.circle_bg_blue_d;
                        case EnConstant.kDangerous:
                            return R.color.circle_bg_red_d;
                        default:
                            return R.color.circle_bg_green_d;
                    }
                } else {
                    return R.color.lpq_color;
                }
        }

    }

    private String getDayNumber(int i) {


        if (App.status == 1) {
            if (App.dayUnitDSOutputsList.get(i).getPeriod(App.status).equals("yjq")) {
                return App.dayUnitDSOutputsList.get(i).homePageOvulation + "";
            } else {
                return App.dayUnitDSOutputsList.get(i).homePageNextMenstruation + "";
            }
        } else {
            if (App.dayUnitDSOutputsList.get(i).homePageOvulation > -1) {
                return App.dayUnitDSOutputsList.get(i).homePageOvulation + "";
            } else {
                return App.dayUnitDSOutputsList.get(i).homePageNextMenstruation + "";
            }
        }
    }


    private String getDayTitle(int i) {

        switch (App.status) {
            case 0:
                switch (App.dayUnitDSOutputsList.get(i).getPeriod(App.status) + "") {
                    case "yjq":
                        return this.getString(R.string.distance_of_ovulation);
                    case "lpq":
                        return this.getString(R.string.distance_of_ovulation);
                    case "plr":
                        return this.getString(R.string.distance_of_ovulation);
                    case "plq":
                        if (App.dayUnitDSOutputsList.get(i).homePageOvulation < 0) {
                            return this.getString(R.string.next_time_menstruation);
                        } else return this.getString(R.string.distance_of_ovulation);
                    default:
                        return this.getString(R.string.next_time_menstruation);
                }
            default:
                switch (App.dayUnitDSOutputsList.get(i).getPeriod(App.status) + "") {
                    case "yjq":
                        return this.getString(R.string.distance_of_ovulation);
                    default:
                        return this.getString(R.string.next_time_menstruation);
                }
        }
    }

    private String getState(int i) {
        switch (App.dayUnitDSOutputsList.get(i).getPeriod(App.status) + "") {
            case "yjq":
                return getString(R.string.menstruation);
            case "lpq":
                return getString(R.string.follicular_phase);
            case "htq":
                return getString(R.string.luteal);
            case "jhaqq":
                return getString(R.string.safe);
            case "wxq":
                return getString(R.string.dangerous);
            case "jqaqq":
                return getString(R.string.safe);
            case "aqq":
                return getString(R.string.safe);
            default:
                if (App.dayUnitDSOutputsList.get(i).homePageOvulation > 0) {
                    return getString(R.string.ovulation);
                } else if (App.dayUnitDSOutputsList.get(i).homePageOvulation == 0) {
                    return getString(R.string.ovulation_day);
                } else {
                    return getString(R.string.after_ovulation);
                }
        }

    }


    private String getPercentNumber(int i) {
        switch (App.dayUnitDSOutputsList.get(i).getPeriod(App.status) + "") {
            case "yjq"://距离月经结束
                return App.dayUnitDSOutputsList.get(i).homePageMenstruationEnd + "";
            default://怀孕概率
                return new java.text.DecimalFormat("#.#").format(App.dayUnitDSOutputsList.get(i).homePageConceptionChance * 100) + "";
        }
    }

    private String getPercentTitle(int i) {
        switch (App.dayUnitDSOutputsList.get(i).getPeriod(App.status) + "") {
            case "yjq":
                return this.getString(R.string.period_end);
            default:
                return this.getString(R.string.probability_of_pregnancy);
        }
    }


    private void toToday(int position) {
        viewPager.setCurrentItem(position);

    }

    @Subcriber
    private void changeState(ChooseStateMsg mState) {
        App.status = mState.getState();
        initCalendar(view);
        StatusBarUtil.setColor(getActivity(), getResources().getColor(R.color.orange), 0);
    }

    @Subcriber
    private void updateAlgorithm(AlgoUpdateMsg algoUpdateMsg) {

        int respCode = algoUpdateMsg.getRespCode();
        AppLog.i("wzz----开始更新UI----"+respCode);
        if (respCode == 1) {

            if (App.dayUnitDSOutputsList.size() == 0) {
                dbManager.initDayUnitDSOutputsList2Memory(App.userName);
                EventBus.getDefault().post(new WebviewInitDataMsg());
            }

            AppLog.i("wzz----开始更新UI----aaa");
            initCalendar(view);
            AppLog.i("wzz----开始更新UI----bbb");
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
                progressDialog = null;
            }
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (viewPager != null && viewPager.getCurrentItem() != 0) {
                StatusBarUtil(viewPager.getCurrentItem());
            }

        }

    }

    private Boolean getAllTask() {

        OKHttpUtil okHttpUtil = new OKHttpUtil(getActivity());
        String appendUrl = "task/getAllTask.json";
        try {
            okHttpUtil.add("authToken", App.authToken);
            okHttpUtil.add("language", "ch");
            okHttpUtil.postAsync(appendUrl, okHttpUtil.new BaseCallBack() {
                        @Override
                        public void onFailure(Request request, IOException e) {
                            super.onFailure(request, e);
                        }

                        @Override
                        public void onResponse(Response response) throws IOException {
                            String respStr = response.body().string();

                            try {
                                JSONObject respJSONObj = new JSONObject(respStr);
                                int respCode = respJSONObj.getInt("code");

                                if (App.HTTP_RESP_OK == respCode) {
                                    GetAllTask getAllTask = JSON.parseObject(respStr, GetAllTask.class);
                                    if (getAllTask != null) {

                                        dbManager.initTaskDetail(1, App.userName, 1, 1,
                                                getAllTask.getSysTask().get(0).getKey().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", "")
                                                , getAllTask.getSysTask().get(0).getKeyEn().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                "基础体温", "BBT",
                                                "48c3fc", "3DB4F9", 2, 6, 8, 11, getAllTask.getSysTask().get(1).getDate(), "测量基础体温", "Measure BBT ");

                                        dbManager.initTaskDetail(2, App.userName, 1, 1, "", "", "", "",
                                                "", "1178E7", -1, -1, -1, -1, getAllTask.getSysTask().get(1).getDate(), "饮水6-8杯", "6-8 glasses of water");

                                        dbManager.initTaskDetail(3, App.userName, 1, 1,
                                                getAllTask.getSysTask().get(2).getKey().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                getAllTask.getSysTask().get(2).getKeyEn().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                "叶酸", "Folic Acid",
                                                "8F40DE", "8F40DE", 2, 4, 5, 15, getAllTask.getSysTask().get(2).getDate(), "服用叶酸", "Take Folic Acid");

                                        dbManager.initTaskDetail(4, App.userName, 1, 1, "", "", "", "",
                                                "", "9A7EE3", -1, -1, -1, -1, getAllTask.getSysTask().get(1).getDate(), "健身运动", "Working out");

                                        dbManager.initTaskDetail(5, App.userName, 1, 1, "", "",
                                                "", "", "", "41CF74", -1, -1, -1, -1, getAllTask.getSysTask().get(1).getDate(), "吃水果", "Daily Fruits");

                                        dbManager.initTaskDetail(6, App.userName, 1, 1,
                                                getAllTask.getSysTask().get(5).getKey().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", "")
                                                , getAllTask.getSysTask().get(5).getKeyEn().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                "宫颈粘液", "Cervical Mucus",
                                                "cf7edd", "C363D5", 2, 6, 6, 20, getAllTask.getSysTask().get(1).getDate(), "观察宫颈粘液", "Check Cervical Mucus");
                                        dbManager.initTaskDetail(7, App.userName, 1, 1,
                                                getAllTask.getSysTask().get(6).getKey().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", "")
                                                , getAllTask.getSysTask().get(6).getKeyEn().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                "排卵试纸", "Test",
                                                "85CC54", "F9575C", 2, 6, 10, 14, getAllTask.getSysTask().get(1).getDate(), "测试排卵试纸", "Ovulation Test");
                                        dbManager.initTaskDetail(8, App.userName, 1, 1,
                                                getAllTask.getSysTask().get(7).getKey().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", "")
                                                , getAllTask.getSysTask().get(7).getKeyEn().split(":")[1].replace("\\n", "\n").replace("}", " ").replace("\"", ""),
                                                "B超", "Ultrasound",
                                                "F6BE3A", "FDB50A", 0, 2, 0, 10, getAllTask.getSysTask().get(1).getDate(), "B超检查", "Ultrasound Examination");
                                    } else {
//
                                    }
                                } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                                    OKHttpUtil.setNewToken();
                                    getAllTask();
                                } else {
                                    AppLog.i("error code! code = " + respCode);
                                }
                            } catch (JSONException e) {
                                AppLog.i("JSONException e");
                                e.printStackTrace();
                            }
                        }
                    }

            );
        } catch (
                JSONException e
                )

        {
            e.printStackTrace();
        }
        return true;
    }


}
